'use strict';

angular.module('yellowPageZjutApp')
  .controller('YellowPageController', function($scope, $http, $q) {
    $scope.yellowPage = {};

    var groupContact = function(contacts) {
      var count = -1,
        tempCategory = '',
        contactGroups = [];
      for(var i = 0, len = contacts.length; i < len; ++i) {
        if(tempCategory !== contacts[i]['category_contact']) {
          ++count;
          tempCategory = contacts[i]['category_contact'];
          contactGroups.push({
            category: contacts[i]['category_contact'],
            contactNumbers: [
              {
                name: contacts[i]['name_contact'],
                number: contacts[i]['number_contact']
              }
            ]
          });
        } else {
          contactGroups[count].contactNumbers.push({
            name: contacts[i]['name_contact'],
            number: contacts[i]['number_contact']
          });
        }
      }
      return contactGroups;
    };

    var getYpageData = function(zone) {
      var deferred= $q.defer();
      $http.get("./jsons/" + zone)
        .success(function(contacts) {
          deferred.resolve(groupContact(contacts));
        })
        .error(function(error) {
          deferred.reject(error);
        });

      return deferred.promise;
    };

    $scope.yellowPage.changeSchoolZone = function(zone) {
      $scope.yellowPage.schoolZone = zone;
      getYpageData(zone)
        .then(function(result) {
          $scope.yellowPage.contacts = result;
        });
    };
    $scope.yellowPage.changeSchoolZone('pf');

    $scope.yellowPage.contactsFilter = function(query, category) {
      return function contactsFilter(state) {
        if (category.match(query)) {    // 预先判断是否匹配分类
          return true;
        } else {
          return state.name.match(query) ? true : state.number.match(query);
        }
      }
    };

  });
